<template>
  <div class="box">
    <div class="chart">
      <div id="charts" ref="chart">
        <!-- PDF.js will render the PDF here -->
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, onUnmounted, ref } from "vue";
import * as pdfjsLib from "pdfjs-dist/webpack";

export default {
  name: "Features",
  mounted() {
    this.$emit("changeTimeIndex", 18);
    this.$emit("changeIsSelect2", true);
    this.$emit("changeIsSelect3", false);
    this.$emit("changeIsTimeOperator", false);
  },
  setup() {
    const chart = ref(null);
    let isUnmounted = false;

    const renderPage = (pdf, pageNum) => {
      pdf.getPage(pageNum).then((page) => {
        if (isUnmounted || !chart.value) return;

        console.log(`Page ${pageNum} loaded`);

        // Calculate the scale to fit the chart container width
        const containerWidth = chart.value.clientWidth;
        const viewport = page.getViewport({ scale: 1 });
        const scale = containerWidth / viewport.width;

        const scaledViewport = page.getViewport({ scale });

        // Prepare canvas using PDF page dimensions
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.height = scaledViewport.height;
        canvas.width = scaledViewport.width;

        // Append canvas to the chart div
        chart.value.appendChild(canvas);

        // Render PDF page into canvas context
        const renderContext = {
          canvasContext: context,
          viewport: scaledViewport,
        };
        const renderTask = page.render(renderContext);
        renderTask.promise.then(() => {
          console.log(`Page ${pageNum} rendered`);
          if (!isUnmounted && pageNum < pdf.numPages) {
            renderPage(pdf, pageNum + 1);
          }
        });
      });
    };

    onMounted(() => {
      const url = "/Features.pdf";
      const loadingTask = pdfjsLib.getDocument(url);

      loadingTask.promise.then((pdf) => {
        if (isUnmounted) return;

        console.log("PDF loaded");

        // Start rendering from the first page
        renderPage(pdf, 1);
      }).catch((reason) => {
        // PDF loading error
        console.error(reason);
      });
    });

    onUnmounted(() => {
      isUnmounted = true;
    });

    return {
      chart,
    };
  },
};
</script>

<style scoped lang="scss">
@media screen and (min-width: 700px) {
  .box {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .chart {
    border: 3px double #1996ef;
    background-color: #fff;
    margin: 60px;
    width: 60%;
    height: auto;
    position: relative;

    #charts {
      width: 100%;
      height: 70vh;
      overflow-y: auto;
    }
  }
}
</style>
